aboutsummaryrefslogtreecommitdiffstats
path: root/frontend/src/app/(main)/goals/[id]/page.tsx
blob: cda33c1f86aa9db224a7ce7f09d3ca87a679816b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Edit, ArrowLeft, Loader2, RefreshCw } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { formatCurrency } from "@/lib/utils";
import { api } from "@/lib/api";
import { GoalProgress } from "../components/goals-list";
import { use } from "react";

export default function GoalDetailPage({ params }: { params: { id: string } }) {
  // Unwrap params Promise using React.use()
  const unwrappedParams = use(params);
  const id = unwrappedParams.id;
  const goalId = parseInt(id);
  
  const [goal, setGoal] = useState<GoalWithProgress | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const router = useRouter();
  const { toast } = useToast();

  const fetchGoalDetails = useCallback(async () => {
    try {
      console.log(`Fetching goal details for ID: ${goalId}`);
      setLoading(true);
      
      // Add cache-busting parameter
      const response = await api.get<GoalProgress>(`/goals/${goalId}/progress?cache=${new Date().getTime()}`);
      console.log("Goal details received:", response.data);
      
      // Validate and normalize data
      const data = response.data;
      if (data && data.goal) {
        const sanitizedData = {
          ...data,
          goal: {
            ...data.goal,
            targetAmount: Number(data.goal.targetAmount) || 0,
            currentAmount: Number(data.goal.currentAmount) || 0,
            createdAt: data.goal.createdAt || new Date().toISOString(),
          },
          percentComplete: Number(data.percentComplete) || 0,
          amountRemaining: Number(data.amountRemaining) || 0,
          daysRemaining: Number(data.daysRemaining) || 0,
          requiredPerDay: Number(data.requiredPerDay) || 0,
          requiredPerMonth: Number(data.requiredPerMonth) || 0,
        };
        console.log("Processed goal data:", sanitizedData);
        setGoal(sanitizedData);
      } else {
        console.error("Invalid goal data format:", data);
        throw new Error("Invalid goal data received");
      }
    } catch (error) {
      console.error("Error fetching goal details:", error);
      toast({
        title: "Error",
        description: "Failed to fetch goal details. Please try again.",
        variant: "destructive",
      });
      router.push("/goals");
    } finally {
      setLoading(false);
    }
  }, [goalId, toast, router]);

  // Fetch goal details when component mounts
  useEffect(() => {
    if (!id) {
      toast({
        title: "Error",
        description: "Goal ID is missing. Please try again.",
        variant: "destructive",
      });
      router.push("/goals");
      return;
    }

    fetchGoalDetails();
  }, [id, fetchGoalDetails, router, toast]);

  const recalculateProgress = async () => {
    if (isNaN(goalId)) {
      toast({
        title: "Error",
        description: "Invalid goal ID",
        variant: "destructive",
      });
      return;
    }
    
    try {
      setRefreshing(true);
      await api.post(`/goals/${goalId}/recalculate`);
      toast({
        title: "Progress recalculated",
        description: "Your goal progress has been recalculated based on transactions.",
      });
      fetchGoalDetails();
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to recalculate goal progress. Please try again.",
        variant: "destructive",
      });
      console.error("Error recalculating goal progress:", error);
    } finally {
      setRefreshing(false);
    }
  };

  if (loading) {
    return (
      <div className="container mx-auto py-8 flex justify-center items-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  if (!goal) {
    return (
      <div className="container mx-auto py-8 text-center">
        <p className="mb-4">Goal not found or access denied.</p>
        <Link href="/goals">
          <Button>Back to Goals</Button>
        </Link>
      </div>
    );
  }

  const { goal: goalData, percentComplete, amountRemaining, daysRemaining, requiredPerDay, requiredPerMonth, onTrack } = goal;
  const isCompleted = goalData.status === "Achieved";

  return (
    <div className="container mx-auto py-8">
      <div className="mb-6">
        <Link href="/goals">
          <Button variant="ghost" size="sm">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Goals
          </Button>
        </Link>
      </div>

      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{goalData.name}</h1>
          <p className="text-muted-foreground">
            {isCompleted
              ? "Goal has been achieved 🎉"
              : onTrack
              ? "Progress is on track"
              : "Progress is behind schedule"}
          </p>
        </div>
        <div className="flex space-x-3 mt-4 md:mt-0">
          <Button
            variant="outline"
            size="sm"
            onClick={recalculateProgress}
            disabled={refreshing}
          >
            {refreshing ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <RefreshCw className="mr-2 h-4 w-4" />
            )}
            Recalculate
          </Button>
          <Link href={`/goals/edit/${goalData.id}`}>
            <Button variant="outline" size="sm">
              <Edit className="mr-2 h-4 w-4" />
              Edit
            </Button>
          </Link>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-2">
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle>Goal Progress</CardTitle>
              <Badge variant={isCompleted ? "default" : onTrack ? "outline" : "destructive"}>
                {isCompleted ? "Achieved" : onTrack ? "On Track" : "Behind"}
              </Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="mb-6">
              <div className="flex justify-between mb-2">
                <span>Completion</span>
                <span>{Math.round(percentComplete)}%</span>
              </div>
              <Progress value={percentComplete} className="h-3" />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div>
                  <h3 className="text-sm font-medium text-muted-foreground mb-1">Target Amount</h3>
                  <p className="text-2xl font-semibold">{formatCurrency(goalData.targetAmount)}</p>
                </div>
                <div>
                  <h3 className="text-sm font-medium text-muted-foreground mb-1">Current Amount</h3>
                  <p className="text-2xl font-semibold">{formatCurrency(goalData.currentAmount)}</p>
                </div>
                <div>
                  <h3 className="text-sm font-medium text-muted-foreground mb-1">Remaining</h3>
                  <p className="text-2xl font-semibold">{formatCurrency(amountRemaining)}</p>
                </div>
              </div>

              <div className="space-y-4">
                {goalData.targetDate && (
                  <div>
                    <h3 className="text-sm font-medium text-muted-foreground mb-1">Target Date</h3>
                    <p className="text-xl font-semibold">{new Date(goalData.targetDate).toLocaleDateString()}</p>
                  </div>
                )}
                {daysRemaining > 0 && (
                  <>
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground mb-1">Days Remaining</h3>
                      <p className="text-xl font-semibold">{daysRemaining} days</p>
                    </div>
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground mb-1">Required Per Day</h3>
                      <p className="text-xl font-semibold">{formatCurrency(requiredPerDay)}</p>
                    </div>
                    <div>
                      <h3 className="text-sm font-medium text-muted-foreground mb-1">Required Per Month</h3>
                      <p className="text-xl font-semibold">{formatCurrency(requiredPerMonth)}</p>
                    </div>
                  </>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Goal Details</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-1">Goal Name</h3>
                <p className="font-medium">{goalData.name}</p>
              </div>
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-1">Purpose</h3>
                <p>{goalData.name}</p>
              </div>
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-1">Status</h3>
                <p>{goalData.status}</p>
              </div>
              <div>
                <h3 className="text-sm font-medium text-muted-foreground mb-1">Created</h3>
                <p>{new Date(goalData.createdAt).toLocaleDateString()}</p>
              </div>
              {isCompleted ? (
                <div className="pt-4">
                  <div className="p-4 bg-green-50 dark:bg-green-950 text-green-700 dark:text-green-300 rounded-md">
                    <p className="font-semibold">🎉 Goal achieved!</p>
                    <p className="text-sm mt-1">
                      Congratulations on achieving your financial goal.
                    </p>
                  </div>
                </div>
              ) : (
                <div className="pt-4">
                  <Link href={`/transactions?goalId=${goalData.id}`}>
                    <Button variant="secondary" className="w-full">View Related Transactions</Button>
                  </Link>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}